package com.example.actflow.fragment;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;


import com.example.actflow.view.FileExplorerView;
import com.example.actflow.MainActivity;
import com.example.actflow.R;
import com.example.actflow.model.AppInfo;
import com.example.actflow.model.Appconfig;
import com.example.actflow.repository.ContextData;
import com.example.actflow.model.LogicItem;
import com.example.actflow.util.LogicItemParser;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class FlowConfigFragment extends Fragment {

    private LinearLayout flowRoot;
    private Spinner appSpinner;
    private FileExplorerView fileExplorer;
    private Switch onStatus;
    private ContextData contextData;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_flow_config, container, false);



        flowRoot = root.findViewById(R.id.flowRoot);
        appSpinner = root.findViewById(R.id.appSpinner);
        fileExplorer = root.findViewById(R.id.file_explorer);
        onStatus = root.findViewById(R.id.onStatus);
        contextData = ContextData.getInstance(getContext());

        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        updateView();

        Button showTextButton = view.findViewById(R.id.showText);

        showTextButton.setOnClickListener(v -> {
            String prettyText = logicItemToPrettyText(contextData.getRoot(), 0);

            HorizontalScrollView horizontalScrollView = new HorizontalScrollView(getContext());
            EditText input = new EditText(getContext());

            input.setText(prettyText);
            input.setMinHeight(600);
            input.setTextIsSelectable(true);
            input.setGravity(Gravity.TOP | Gravity.START);
            input.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
            input.setVerticalScrollBarEnabled(true);
            input.setHorizontallyScrolling(true); // 允许横向滚动
            input.setMovementMethod(new ScrollingMovementMethod());
            input.setSingleLine(false);

            // 设置最小宽度（确保可以横向滚动）
            input.setMinWidth(2000); // 根据内容调整

            horizontalScrollView.addView(input);

            // 创建弹窗
            AlertDialog dialog = new AlertDialog.Builder(getContext())
                    .setTitle("查看配置结构")
                    .setView(horizontalScrollView)
                    .setNeutralButton("复制", (d, which) -> {
                        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("config_pretty", input.getText().toString());
                        clipboard.setPrimaryClip(clip);
                        Toast.makeText(getContext(), "已复制到剪贴板", Toast.LENGTH_SHORT).show();
                    })
                    .setNegativeButton("导入", (d, which) -> {
                        // 空实现，实际处理在show()之后
                    })
                    .setPositiveButton("关闭", null)
                    .create();

            // 显示后获取按钮并设置监听
            dialog.setOnShowListener(d -> {
                Button importButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
                importButton.setOnClickListener(v1 -> {
                    String textToImport = input.getText().toString();
                    try {
                        LogicItem rootItem = LogicItemParser.parse(textToImport);

                        contextData.setRoot(rootItem);
                        fileExplorer.updateView();

                        dialog.dismiss();
                        contextData.saveConfigForApp();
                        Toast.makeText(getContext(), "导入成功。", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(getContext(), "错误："+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            });
            dialog.show();
        });


        Button clearTextButton = view.findViewById(R.id.clearText);

        clearTextButton.setOnClickListener(v -> {
            contextData.clearRoot();
            fileExplorer.updateView();
        });

    }

    public void updateView(){
        //控件未渲染
        if(contextData == null){
            return;
        }
        updateAppSpinner();
        fileExplorer.updateView();
    }

    public void updateAppSpinner() {

        // 把 App 名称提取出来作为 Spinner 数据
        List<String> appNames = new ArrayList<>();
        for (Appconfig appConfig : contextData.getAppConfigs()) {
            if(appConfig.appInfo!=null){
                appNames.add(appConfig.appInfo.appName);
            }
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(),
                android.R.layout.simple_spinner_item, appNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // ✅ 绑定 Adapter
        appSpinner.setAdapter(adapter);

        // 设置监听器
        appSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedAppName = (String) parent.getItemAtPosition(position);
                // 找到对应的 AppInfo
                for (Appconfig config : contextData.getAppConfigs()) {
                    if (config.appInfo.appName.equals(selectedAppName)) {
                        contextData.loadPackage(config.appInfo);
                        fileExplorer.updateView();
                        break;
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        boolean enable = false;
        // 自动选中当前 app
        if(contextData.selectedAppInfo!=null){
            String currentApp = contextData.selectedAppInfo.appName;
            if (currentApp != null) {
                int index = appNames.indexOf(currentApp);
                if (index >= 0) {
                    appSpinner.setSelection(index);
                }
            }
            String packageName = contextData.selectedAppInfo.packageName;
            Optional<Appconfig> first = contextData.getAppConfigs().stream().filter(d -> d.appInfo.packageName.equals(packageName)).findFirst();
            if(first.isPresent() && first.get().isEnable!=null){
                enable = first.get().isEnable;
            }

        }

        onStatus.setChecked(enable);

        onStatus.setOnCheckedChangeListener((buttonView, isChecked)->{
            AppInfo selectedAppInfo = contextData.selectedAppInfo;
            if (selectedAppInfo != null) {
                String packageName = selectedAppInfo.packageName;
                contextData.setEnable(packageName,isChecked);
            }
        });


    }


    private String logicItemToPrettyText(LogicItem item, int indent) {
        StringBuilder sb = new StringBuilder();

        String prefix = "    ".repeat(indent);
        String typeStr = item.type == LogicItem.Type.CONDITION ? "[条件]" : "[动作]";
        String compare = item.compareOp != null && !item.compareOp.isEmpty() ? item.compareOp : "";
        String param = item.param != null ? item.param : "";
        String varName = item.varName != null ? item.varName : "";
        String target = item.target != null ? item.target : "";
        String actionType = item.actionType != null ? item.actionType : "";
        Double delay = item.delay !=null ? item.delay : 0.0;


        if (item.type == LogicItem.Type.CONDITION) {
            sb.append(prefix).append(typeStr)
                    .append(" ").append(target).append(" ").append(compare).append("(\"").append(param).append("\")");
            if (!varName.isEmpty()) {
                sb.append(" ").append(varName);
            }
            sb.append("\n");
        } else {
            sb.append(prefix).append(typeStr)
                    .append(" ").append(target)
                    .append(" ").append(actionType)
                    .append(" ").append(param.isEmpty() ? "" : "(\"" + param + "\")")
                    .append(" ").append("延迟(\"").append(formatDouble(delay)).append("\")")
                    .append("\n");
        }

        for (LogicItem child : item.children) {
            sb.append(logicItemToPrettyText(child, indent + 1));
        }

        return sb.toString();
    }

    public static String formatDouble(double value) {
        DecimalFormat df = new DecimalFormat("0.##"); // 最多保留2位小数，末尾0自动去除
        return df.format(value);
    }

}

